package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void submit(Order order) {
        //获取当前登录用户
        User user = UserHolder.get();
        //查询到当前用户的购物车
        List<Cart> cartList = cartService.findByCart();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空，请添加商品");
        }
        //根据前端传入的地址id查询地址信息
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空，查询不到");
        }
        //4. 手动使用雪花算法生一个订单id
        long id = IdWorker.getId();//雪花算法id
        //double decimal = 0
        BigDecimal decimal = new BigDecimal(0);
        //5. 生成订单详情
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(id);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());
            //保存到数据表
            orderDetailMapper.insert(orderDetail);
            //每次遍历的时候添加金额
            //decimal += number * amount
            decimal = decimal.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        //生成订单
            order.setId(id);
            order.setNumber(id+"");
            order.setStatus(0);
            order.setUserId(user.getId());
            order.setOrderTime(new Date());
            order.setCheckoutTime(new Date());
            order.setAmount(decimal);
            order.setUserName(user.getName());
            order.setPhone(address.getPhone());
            order.setAddress(address.getDetail());
            order.setConsignee(address.getConsignee());
            orderMapper.insert(order);
        //清空当前用户购物车
            cartService.clean();
    }

    @Override
    public Page<Order> findList(Integer pageNum, Integer pageSize, Long number, Date beginTime, Date endTime) {
        Page<Order> page = new Page<>(pageNum,pageSize);
        //设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number!=null,Order::getId,number )
                .ge(beginTime!=null,Order::getOrderTime,beginTime )
                .le(endTime!=null,Order::getOrderTime,endTime )
                    .orderByDesc(Order::getOrderTime);
        //4. 执行查询,得到订单信息
        page = orderMapper.selectPage(page, wrapper);
        //5. 遍历订单列表,得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6. 根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        return page;
    }

    @Override
    public Page<Order> findPage(Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId())
                .orderByDesc(Order::getOrderTime);
        page = orderMapper.selectPage(page, wrapper);
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }
        return page;

    }

}
